<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>flex仿知乎首页</title>
  <link rel="stylesheet" type="text/css" href="../css/zhihu.css" />
  <link rel="stylesheet" type="text/css" href="../css/messages.css" />
  <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
  <link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
  <script src="https://unpkg.com/coco-message/coco-message.min.js"></script>
  <script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div>
  <div class="header" id="header">
    <ul class="ul-head-left">
      <li class="li-head-left" style="margin-left: 120px; margin-top: 20px;"><img src="../imgs/index-imgs/zhihu-img.png" style="width: 50px" alt="zhihu" class="zhihu"></li>
      <li class="li-head-left" style="border-bottom: 5px #098dee solid;"><a href="homePage.jsp" target="menuFrame"><p id="jump" >首页</p></a> </li>
      <li class="li-head-left">发现</li>
      <li class="li-head-left">等你来答</li>

    </ul>
    <div class="center">
      <label  class="select-label">
        <input type="text" placeholder="请搜索" id="selectTitle" class="select-input">
        <img src="../imgs/index-imgs/select-img.png" alt="" id="selectAll" class="select-img">
      </label>
      <button class="quiz-button" >提问</button>
    </div>
    <!--  右侧 -->
    <ul class="right ul-head-left">
      <li class="item">
        <div style="position:relative;">
          <div style="padding-top: 15px;" id="oinformationDiv">
            <a href="#" style="margin-top: 15px" id="oinformationA">
              <img id="oinformationImg" src="../imgs/index-imgs/message-img.png" style="width: 20px;margin: 0 2px -2px 2px;color: #8a8a8a;"><br>
              <span id="oinformationSpan" style="font-size: 14px;color: #8a8a8a;">消息</span>
            </a>
          </div>
          <div class="dropdown-news">
            <div class="dropdown-div-transition"></div>
            <div id="myDropdownNews"  class="dropdown-content-news">
              <div class="dropdown-content-news-top">
                <ul>
                  <li id="li-invite-answer" onclick="recentlyInviteAnswer()">
                    <i id="i-invite-answer" class="fa fa-list-ul"></i>
                  </li>
                  <li id="li-recently-attention" onclick="recentlyInterestMe()" style="border-left: 1px solid #d2d2d2;border-right: 1px solid #d2d2d2;margin-top: 0px;">
                    <i id="i-recently-attention"  class="fa fa-user"></i>
                  </li>
                  <li id="li-like" style="margin-top: 0px;" onclick="recentlyLikesMy()">
                    <i id="i-like" class="fa fa-heart"></i>
                  </li>
                </ul>
              </div>
              <div class="dropdown-content-news-content">
                <div id="newsContent" style="height: 100%;overflow: auto">

                </div>
              </div>
              <div id="newsBottom" class="dropdown-content-news-bottom">
                <a id="notificationSettings" href="#"><i class="fa fa-gear" style="font-size: 15px;margin-right: 5px;"></i>设置</a>
                <a href="#">查看全部通知</a>
              </div>
            </div>
          </div>
        </div>
      </li>
      <li class="item">
        <div class="dropdown" id="message-userImg" style="cursor: pointer;">
          <i id="i-icon" class="fa fa-circle" style="color:red;position: absolute;font-size: 10px;display: none"></i>
          <img id="message-sixin" src="../imgs/index-imgs/private-letter-img.png" tabindex="-1" style="width: 20px;margin: 0 2px -2px 2px;color: #8a8a8a;">
          <span style="font-size: 14px;color: #8a8a8a;" id="message-span">私信</span>
          <div id="messageMyDropdown" class="dropdown-content">
            <span style="width: 90%;display: inline-block;text-align: center;padding: 10px">我的私信</span>
            <hr>
            <div id="user-content">
            </div>
            <a id="tz-message" href="message.jsp" target="menuFrame" style="cursor: pointer;position: absolute;bottom: 15px;right: 15px;color: #9aa5b5" >查看全部私信</a>
          </div>
        </div>
      </li>
      <li>
        <div class="dropdown-user">
          <img src="" tabindex="-1" id="userImg" style="size: 6px;width: 35px;margin-left: 20px;cursor: pointer;">
          <div id="myDropdown" class="dropdown-content-user-menu">
            <a href="personalPage.jsp" target="menuFrame" class="a-bgColor"  style="margin-top: 5px;" id="personal-center" >
              <img src="../imgs/other-imgs/个人中心.png">
              <span style="color: #8a8a8a;" class="zhuye-span">我的主页</span>
            </a>
            <a href="#" class="a-bgColor" id="barrierFree" onclick="messageAlert()">
              <img src="../imgs/other-imgs/无障碍.png" id="barrierFreeImg">
              <span style="color: #8a8a8a;" id="barrierFreeSpan">无障碍</span>
            </a>
            <a href="#" class="a-bgColor" id="solicitude" onclick="messageAlert()">
              <img src="../imgs/other-imgs/老年人.png" id="solicitudeImg">
              <span style="color: #8a8a8a;" id="solicitudeSpan">关怀版</span>
            </a>
            <a href="#" class="a-bgColor" id="install" onclick="messageAlert()">
              <img src="../imgs/other-imgs/设置.png" id="installImg">
              <span style="color: #8a8a8a;" id="installSpan">设置</span>
            </a>
            <a href="#" class="a-bgColor" style="margin-bottom: 5px;" onclick="logout()">
              <img src="../imgs/other-imgs/退出.png">
              <span style="color: #8a8a8a;">退出</span>
            </a>
          </div>
        </div>
      </li>
    </ul>
  </div>
  </div>

<div id="window" class="window_css_message">


</div>
<!--出现悬浮窗口后,背景变暗-->
<div id="shadow" class="shadow_css_message"></div>

<div class="layui-body">
  <iframe id="menuFrame" name="menuFrame" src="" style="overflow: visible;" scrolling="yes" frameborder="no"
          width="100%" height="100%">
  </iframe>
</div>
</body>
  <script>
    "use strict";
    let selectTitleValue = "";
    function variableParent(){
      return userId;
    }
    handleJump();
    selectUser();
    function handleJump() {
      $("#jump").click();
    }

    function scrollHeight(){
      var container = $('.window_css_dialogue_message');
      // 设置滚动条位置为最底部
      container.scrollTop(container[0].scrollHeight);
    }

    $("#selectAll").click(function(){
      let selectTitle = $("#selectTitle")
      var iframe = document.getElementById('menuFrame').contentWindow.document;
      if (iframe.URL!='http://localhost:8080/zhihu1/view/homePage.jsp'){
        handleJump();
        setTimeout(function(){
          document.getElementById('menuFrame').contentWindow.selectCard(selectTitle.val());
        }, 50);
      }else {
        document.getElementById('menuFrame').contentWindow.selectCard(selectTitle.val());
      }
    });

    let userId1 = 0;
    let userImg2 = null;
    let userId = 0;
    let ouserImg = $("#userImg");
    let messageUserImg = $("#message-userImg");
    let userStatus = null;
    <% Object username = session.getAttribute("username");%>
    function selectUser() {
      $.ajax({
        async: true,
        url: "http://localhost:8080/zhihu1/user?ac=selectUser",
        type: "post",
        data: {
          username: "<%=username %>"
        },
        dataType: "json",
        success: function (data) {
          userStatus = data.data[0].userStatus;
          userId = data.data[0].id;
          ouserImg.attr("src", data.data[0].img);
        }
      })
    };

    $("html").on("click",function (event){
      if(event.target.id !="userImg" && event.target.id != "barrierFree" && event.target.id != "barrierFreeImg" && event.target.id != "barrierFreeSpan" && event.target.id != "solicitude" && event.target.id != "solicitudeImg" && event.target.id != "solicitudeSpan" && event.target.id != "solicitude" && event.target.id != "install"  && event.target.id != "installImg" && event.target.id != "installSpan"){
        $("#myDropdown").css("display","none");
      }
      if(event.target.id != "newsContent" && event.target.id != "li-like" && event.target.id != "i-like" && event.target.id != "li-recently-attention" && event.target.id != "i-recently-attention" && event.target.id != "li-invite-answer" && event.target.id != "i-invite-answer" && event.target.id != "newsBottom" && event.target.id != "notificationSettings" && event.target.id != "myDropdownNews" && event.target.id !="oinformationA" && event.target.id !="oinformationImg" && event.target.id !="oinformationSpan"){
        $(".dropdown-news").css("display","none");
      }
      if(event.target.id != 'message-userImg' && event.target.id !="message-span" && event.target.id !="message-sixin" && event.target.id !="messageMyDropdown"){
        close()
      }
    })

    $("#oinformationA").on("click",function (){
      $(".dropdown-news").css("display","block");
      $("#i-invite-answer").css("color","#098dee");
      $("#i-recently-attention").css("color","#9aa5b5");
      $("#i-like").css("color","#9aa5b5");
      $("#newsContent").empty();
      recentlyInviteAnswer();
    })
    $("#oinformationImg").on("click",function (){
      $(".dropdown-news").css("display","block");
      $("#i-invite-answer").css("color","#098dee");
      $("#i-recently-attention").css("color","#9aa5b5");
      $("#i-like").css("color","#9aa5b5");
      $("#newsContent").empty();
      recentlyInviteAnswer();
    })
    $("#oinformationSpan").on("click",function (){
      $(".dropdown-news").css("display","block");
      $("#i-invite-answer").css("color","#098dee");
      $("#i-recently-attention").css("color","#9aa5b5");
      $("#i-like").css("color","#9aa5b5");
      $("#newsContent").empty();
      recentlyInviteAnswer();
    })


    //近七天关注我的用户
    function recentlyInterestMe(){
      $("#i-recently-attention").css("color","#098dee");
      $("#i-invite-answer").css("color","#9aa5b5");
      $("#i-like").css("color","#9aa5b5");

      $("#newsContent").empty();
      var aa = `<div style="height: 100%;text-align: center;color: #9aa5b5;">
                        <img src="../imgs/other-imgs/message-img.png">
                        <p>还没有消息</p>
                      </div>`;
      $("#newsContent").append(aa);

      $.ajax({
        type: "post",
        url: "http://localhost:8080/zhihu1/newInformation?ac=queryRecentlyInterestMe",
        dataType: "json",
        data:{
          "userId": userId
        },success:function (data){
          let list = data.data;
          $("#newsContent").empty();

          if (list.length <= 0){
            let aa = `<div style="height: 100%;text-align: center;color: #9aa5b5;">
                        <img src="../imgs/other-imgs/message-img.png">
                        <p>还没有消息</p>
                      </div>`;
            $("#newsContent").append(aa);
          }else {
            let contentTop = `<div style="height: 45px;display: flex;align-items: center;justify-content: center;margin: 0 13px;border-bottom: 1px solid #e0dede;">
                                <p style="font-size: 13px;color: #d2d2d2;">近七天内关注你的人</p>
                            </div>`;
            $("#newsContent").append(contentTop);

            for (let i = 0; i < list.length; i++) {
              let newsUser = `<a href="personalPage.jsp?username1=`+list[i].user_name+`" target="menuFrame">
                                <div style="height: 60px;margin: 0 13px;display: flex;align-items: center;">
                                    <div style="display: flex;width: 100%">
                                      <div>
                                        <img src="`+list[i].img+`" style="width: 42px;border-radius: 5px;">
                                      </div>
                                      <div id="users`+list[i].id+`" style="display: flex;flex-direction: column;justify-content: space-between;">
                                      </div>
                                    </div>
                                   </div>
                                </a>`;
              $("#newsContent").append(newsUser);


              if (list[i].introduce == null){
                let introduce1 = `<span style="font-weight: 600;">`+list[i].user_name+`</span>`;
                $("#users"+list[i].id).append(introduce1);
              }else {
                let introduce2 = `<span style="font-weight: 600;">`+list[i].user_name+`</span>
                                    <span style="font-size: 13px;color: #6d6767;">`+list[i].introduce+`</span>`;
                $("#users"+list[i].id).append(introduce2);
              }
            }
          }
        },error:function (error){
          console.log(error);
        }
      })
    }

    //最近五条谁点赞了我发布帖子
    function recentlyLikesMy(){
      $("#i-like").css("color","#098dee");
      $("#i-invite-answer").css("color","#9aa5b5");
      $("#i-recently-attention").css("color","#9aa5b5");

      $("#newsContent").empty();
      var aa = `<div style="height: 100%;text-align: center;color: #9aa5b5;">
                        <img src="../imgs/other-imgs/message-img.png">
                        <p>还没有消息</p>
                      </div>`;
      $("#newsContent").append(aa);

      $.ajax({
        async: true,
        type: "post",
        url: "http://localhost:8080/zhihu1/newInformation?ac=queryLikesMy",
        dataType: "json",
        data:{
          "userId": userId
        },success:function (data){
          let list = data.data;
          $("#newsContent").empty();

          if (list.length <= 0){
            let aa = `<div style="height: 100%;text-align: center;color: #9aa5b5;">
                        <img src="../imgs/other-imgs/message-img.png">
                        <p>还没有消息</p>
                      </div>`;
            $("#newsContent").append(aa);
          }else {
            let contentTop = `<div style="height: 45px;display: flex;align-items: center;justify-content: center;margin: 0 13px;">
                                <p style="font-size: 13px;color: #d2d2d2;">只显示最近五条点赞信息</p>
                            </div>`;
            $("#newsContent").append(contentTop);

            for (let i = 0; i < list.length; i++) {
              let newsUser = `<div style="margin: 0 13px;">
                                <div style="width: 100%;padding: 10px 0;border-top: 1px solid #e0dede;font-size: 14px">
                                    <a href="personalPage.jsp?username1=`+list[i].user_name+`" target="menuFrame" style="color: #3852a3;margin-right: 3px;text-decoration: none;font-size: 14px;">`+list[i].user_name+`</a>
                                    点赞了我发布的
                                    <a href="#" style="color: #3852a3;margin-left: 3px;text-decoration: none;font-size: 14px;">`+list[i].title+`</a>
                                </div>
                               </div>`;
              $("#newsContent").append(newsUser);
            }
          }
        },error: function (error){
          console.log(error)
        }
      })
    }

    //查看谁邀请我回答问题
    function recentlyInviteAnswer(){
      $("#i-invite-answer").css("color","#098dee");
      $("#i-like").css("color","#9aa5b5");
      $("#i-recently-attention").css("color","#9aa5b5");

      $("#newsContent").empty();

      $("#newsContent").empty();
      var aa = `<div style="height: 100%;text-align: center;color: #9aa5b5;">
                        <img src="../imgs/other-imgs/message-img.png">
                        <p>还没有消息</p>
                      </div>`;
      $("#newsContent").append(aa);
    }
    // 消息-设置按钮
    $("#notificationSettings").on("click",function (){
      cocoMessage.error("此功能暂未开放！！！")
    })

    ouserImg.on("focus",function (event){
      $("#myDropdown").css("display","block");
    })

    messageUserImg.on("click", function () {
      $(".dropdown-content").show();
      $("#i-icon").css("display","none");
      $.ajax({
        async: true,
        url: "http://localhost:8080/zhihu1/message?ac=queryMessage",
        type: "post",
        data: {
          userId: userId
        },
        dataType: "json",
        success: function (data) {
          let questionData = data.data;
          let content = $("#user-content");
          content.empty();

          for (let i = 0; i < 3; i++) {
            let question = questionData[i];

            // 使用正则表达式去除HTML标签
            let cleanContent = question.content.replace(/<.*?>/g, '');

            let questionCard = `
                    <div class="chatlist">
                        <div class="block active" onclick="list(${question.user},'${question.user_name}','${question.img}')">
                        <div class="imgbx">
                            <img src="${question.img}" style="width:30px;height:30px" class="cover">
                        </div>
                        <div class="details">
                            <div class="listHead">
                                <h4>${question.user_name}</h4>
                                <p class="time">${question.create_time}</p>
                            </div>
                            <div class="message_p">
                                <p>${cleanContent}</p>
                            </div>
                        </div>
                        </div>
                    </div>`;

            let messageP = $('<div>').html(questionCard);
            content.append(messageP);
          }
        }
      })
    })

    function prohibition(){
      if(userStatus == 1){
        alert("禁言用户不能进行操作!")
        process.exit();
      }
    }

    function close() {
      $("#messageMyDropdown").css("display", "none");
    }

    /*当点击调用此方法后,将悬浮窗口显示出来,背景变暗*/
    function displayWindow() {
      /*悬浮窗口的显示,需要将display变成block*/
      $("#window").css("display", "block");
      /*将背景变暗*/
      $("#shadow").css("display", "block");
    }

    /*当点击调用此方法,将悬浮窗口和背景全部隐藏*/
    function hideWindow() {
      $("#window").css("display", "none");
      $("#shadow").css("display", "none");
    }

    function list(id, name, img) {
      $.ajax({
        async: true,
        url: "http://localhost:8080/zhihu1/message?ac=queryUserMessage",
        type: "post",
        data: {
          id: id,
          userId: userId
        },
        dataType: "json",
        success: function (data) {
          userId1 = id;
          userImg2 = img;
          displayWindow();
          let questionData = data.data;
          let content = $("#window");
          let questionCard = "";
          content.empty();
          let shujv = "";
          let userImg = ouserImg.attr("src");
          for (let i = 0; i < questionData.length; i++) {
            let question = questionData[i];
            if (question.user1_id == userId) {
              shujv += `<li class="left">
                                    <img style="width:40px;height:40px" src="${userImg2}">
                                    <span>${question.content}</span>
                                </li>`;
            } else if (question.user_id == userId) {
              shujv += `<li class="right">
                                    <img style="width:40px;height:40px" src="${userImg}">
                                    <span>${question.content}</span>
                                </li>`;
            }
            questionCard = `<ul id="div-ul" class="m-ul">
                 ` + shujv + `
                </ul>`;
          }


          let bigDiv = `<h1>${name}</h1>
                        <a class="right_a" href="javascript:void(0)" onclick="hideWindow()">
                            ✕
                        </a>
                        <div class="window_css_dialogue_message">
                        ` + questionCard + `
                        </div>
                         <div id="editor" class="editor" style="height:105px"> </div>
                         <button class="button1" onclick="sending(${id})">发送</button>`;
          content.append(bigDiv);

          let toolbarOptions = [
            ['image'],
          ];

          let quill = new Quill('#editor', {
            modules: {
              toolbar: toolbarOptions
            },
            theme: 'snow'
          });
          close();
          scrollHeight();
        }
      })
    }

    function sending(id) {
      prohibition();
      let content = $(".ql-editor").html();
      if (content != "<p><br></p>") {
        $.ajax({
          async: true,
          url: "http://localhost:8080/zhihu1/message?ac=addMessage",
          type: "post",
          data: {
            id: id,
            userId: userId,
            content: content
          },
          dataType: "json",
          success: function (data) {
            let text = {
              content: content,
              toUserId: id,
              id: userId
            };
            let userImg = ouserImg.attr("src");
            if(data.data == false){
              let right = `<li class="right">
                                    <img style="width:40px;height:40px" src="${userImg}">
                                    <span>${content}</span>
                                    <i title="未互相关注前，不能连续发两条!" class="fa fa-exclamation-circle" style="color:red;font-size:25px;margin:0 10px;"></i>
                                </li>`;
              $("#div-ul").append(right);
              $(".ql-editor").html("");
              scrollHeight();
            }else {
              socket.send(JSON.stringify(text));
              let right = `<li class="right">
                                    <img style="width:40px;height:40px" src="${userImg}">
                                    <span>${content}</span>
                                </li>`;
              $("#div-ul").append(right);
              $(".ql-editor").html("");
              scrollHeight();
            }
          }
        })
      }
    }

    const wsuri = 'ws://localhost:8080/zhihu1/websocket';//ws地址
    let socket = new WebSocket(wsuri);

    socket.addEventListener('open',function (){
      console.log("连接成功")
    })

    socket.addEventListener('message', function (event) {
      let data = JSON.parse(event.data);
      if(data.id == userId1 && data.toUserId == userId){
        let left = `<li class="left">
                    <img style="width:40px;height:40px" src="${userImg2}">
                    <span>${data.content}</span>
                </li>`;
        $("#div-ul").append(left);
        scrollHeight();
      }
      $("#i-icon").css("display","block");
    });
    socket.addEventListener('error', function (error) {
      console.error('WebSocket 发生错误:', error);
    });

    socket.addEventListener('close', function (event) {
      if (event.wasClean) {
        console.log(`连接关闭，状态码：${event.code}, 原因：${event.reason}`);
      } else {
        console.error('连接异常断开');
      }
    });

    let atz = $("#tz-message");
    atz.on("click",function (event){
      event.stopPropagation();
      $("#messageMyDropdown").hide();
    })

    //消息提示
    function messageAlert(){
      cocoMessage.error("此功能暂未开放！！！")
    }

    //退出登录
    function logout(){
      $.ajax({
        async: true,
        type: "post",
        url: "http://localhost:8080/zhihu1/login?ac=logout",
        dataType: "json",
        data:{
          "username": "<%=username %>"
        },success:function (data){
          if (data.data){
            location.href = "../login/login.jsp";
          }else {
            cocoMessage.error("服务器错误，请重试！！！")
          }
        },error:function (error){
          console.log(error);
        }
      })
    }
  </script>
</html>
